let app = getApp();
import regeneratorRuntime from '../../../common/vendor/runtime';

Page({
  _isClick: true,
  interval: null,
  data: {
    check: true,
    this_is_open: true,
    isShow: false,
    wifiList: [],  // 系统默认wifi列表
    name: '', // 点击的wifi名称
    submit: false, // 密码长度超过7位，提交键开启
    errorCode: {
      12000: '未先调用 startWifi 接口',
      12001: '当前系统不支持相关能力',
      12002: '密码错误',
      12003: '连接超时',
      12004: '重复连接 Wi-Fi',
      12005: '未打开 Wi-Fi 开关',
      12006: '未打开 GPS 定位开关',
      12007: '拒绝授权链接 Wi-Fi',
      12008: '无效 SSID',
      12009: '系统运营商配置拒绝连接 Wi-Fi',
      12010: '系统其他错误，需要在 errmsg 打印具体的错误原因',
      12011: '应用在后台无法配置 Wi-Fi',
      12013: '系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试',
    },
    isClick: true,
  },

  async onShow() {
    try {
      const system = await this.wxGetSystemInfo();
      if (system === 'android') {
    this.getList();
      }
      this.interval = setInterval(() => {
        this.checkWifi();
      }, 5000);
      this.setData({
        system
      })
    } catch (error) {
      console.log('======onShow error',error);
    }
  },

  onUnload() {
    clearInterval(this.interval);
  },

  wxStartWifi() { // 初始化 Wi-Fi 模块
    const { errorCode }  = this.data;
    return new Promise((resolve, reject) => {
      wx.startWifi({
        success: res => {
          resolve(true);
  },
        fail: res => {
          console.log('=======wxStartWifi err', res);

          wx.showModal({
            title: '系统提示',
            content: errorCode[res.errCode] || res.errMsg,
            showCancel: false,
        });
          reject(false);
          },
      });
            });
          },

  wxGetWifiList() { // 请求获取 Wi-Fi 列表
    const { errorCode }  = this.data;
    return new Promise((resolve, reject) => {
      wx.getWifiList({
        success: res => {
          resolve(true);
          },
        fail: res => {
          console.log('=======wxGetWifiList err', res);
          wx.showModal({
            title: '系统提示',
            content: errorCode[res.errCode] || res.errMsg,
            showCancel: false,
        });
          reject(false);
      },
    });
    });
  },

  wxOnGetWifiList() { // 监听获取到 Wi-Fi 列表数据事件
    return new Promise(resolve => {
      wx.onGetWifiList(res => {
        resolve(res.wifiList);
              });
              });
  },

  wxGetLocation() { // 获取当前的地理位置
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'wgs84',
        success: res => {
          const location = `${res.longitude},${res.latitude}`;
          resolve(location);
          this.setData({
            location,
              });
          },
        fail: res => {
          console.log('=======wxGetLocation err', res);
          wx.showModal({
            title: '系统提示',
            content: '获取地理位置失败',
        });
          reject(false);
      },
    });
    });
  },

  wxConnectWifi({ name: SSID = '', password = '' }) { // 连接 Wi-Fi
    const { errorCode, isClick } = this.data;
    if (isClick && this._isClick) {
      this.setData({ isClick: false });
      this._isClick = false;
    return new Promise((resolve, reject) => {
        wx.connectWifi({
        SSID,
        password,
        success: res => {
            wx.getConnectedWifi({
              success: res => {
                let onname = res.wifi.SSID;
                if (SSID == onname) {
                  this.recording({ SSID, password});
                  wx.showToast({
                    title: '连接成功',
                  });
                  this.setData({
                    onname: SSID,
                    isShow: false,
                  });
          resolve(true);
                }
              },
              fail: res => {
                wx.showModal({
                  title: '系统提示',
                  content: '连接失败',
                  showCancel: false,
                });
                reject(false);
              },
              complete: res => {
                this.setData({ isClick: true });
                this._isClick = true;
              }
            });
          },
        fail: res => {
          wx.showModal({
            title: '系统提示',
            content: errorCode[res.errCode] || res.errMsg,
            showCancel: false,
          });
          reject(false);
          },
          complete: res => {
            this.setData({ isClick: true });
            this._isClick = true;
          }
        });
    });
    }
  },

  wxGetSystemInfo() { // 获取系统信息
    return new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success: res => {
          resolve(res.platform);
        },
        fail: res => {
          reject(false);
  },
    });
      });
  },

  async getWifiList() {
    try {
      const location = await this.wxGetLocation();
      return new Promise((resolve, reject) => {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
            op: 'getWifiList',
        location,
      },
      module: 'cm_wifi',
          success: res => {
            resolve(res.data.data);
          },
          fail: res => {
            wx.showModal({
              title: '系统提示',
              content: '获取默认WiFi列表失败',
              showCancel: false,
    });
            reject(false);
  },
        });
    });

    } catch (error) {
      console.log('=======getWifiList error', error);
    }
  },

  async getList() {
    try {
      const isAuthorize = await this.checkAuthorize();
      const isStart = await this.wxStartWifi();
      const isGetlist = await this.wxGetWifiList();
      const system = await this.wxGetSystemInfo();
      
      if (isAuthorize && isStart && isGetlist) {
        let wifiList = await this.wxOnGetWifiList();
        let unlockWifiList = await this.getWifiList();
        let arrlist = [];
        if (system == 'android') {
          for (let i = 0; i < wifiList.length; i++) {
            wifiList[i].signalStrength = wifiList[i].signalStrength / 100;
          }
        }

        for (let i = 0; i < unlockWifiList.length; i++) {
          for (let j = 0; j < wifiList.length; j++) {
            if (wifiList[j].SSID == unlockWifiList[i].name) {
              unlockWifiList[i].signalStrength = wifiList[j].signalStrength;
              arrlist.push(unlockWifiList[i]);
            }
          }
        }

        this.setData({
          wifiList,
          arrlist,
            });
      }
    } catch (error) {
      console.log('==========getList error', error);
    }
          },

  async contenting(e) {  // 连接已有密码的wifi
    try {
      const isAuthorize = await this.checkAuthorize();
      const isStart = await this.wxStartWifi();
      if (isAuthorize && isStart) {
        const { name = '', password = '' } = e.currentTarget.dataset;
        await this.wxConnectWifi({ name, password });
      }

    } catch (error) {
      console.log('==========contenting error', error);
    }
          },

  async makeSure() {  // 确认连接wifi
    try {
      const { name = '', password = '' } = this.data;
      const isAuthorize = await this.checkAuthorize();
      const isStart = await this.wxStartWifi();

      if (isAuthorize && isStart) {
        await this.wxConnectWifi({ name, password });
      }
      
    } catch (error) {
      console.log('==========makeSure error', error);
    }
      },

  connect(e) { // 点击连接列表的wifi
    let name = e.currentTarget.dataset.name;
    this.setData({
      name,
      isShow: true,
    });
  },

  bindinput(e) {
    let password = e.detail.value;
    this.setData({
      password,
    });
    if (password.length > 7) {
      this.setData({
        submit: true,
    });
    }
  },

  isOpen() {
    this.setData({
      check: false,
    });
  },

  close() { // 关闭遮罩层
    this.setData({
      isShow: false,
    });
  },

  goTip() {
    app.util.navigateTo('/cm_wifi/pages/success/success', {}, false);
  },

  async onPullDownRefresh() {
    const system = await this.wxGetSystemInfo();
    if (system === 'android') {
      this.getList();
    }
    wx.stopPullDownRefresh();
  },

  onShareAppMessage() {
  },

  checkAuthorize() {
    const scope = 'scope.userLocation';
    return new Promise(resolve => {
      wx.getSetting({
        success: res => {
          if (!res.authSetting[scope]) {
            wx.authorize({
              scope,
              success: res => {
                resolve(true);
              },
              fail: res => {
                resolve(false);
              },
            });
            return;
          }
          resolve(true);
        },
      });
    });
  },

  checkWifi() {
    wx.startWifi({
      success: res => {
        wx.getConnectedWifi({
          success: res => {
            console.log('=======checkWifi',res);
            let onname = res.wifi.SSID;
            this.setData({
              onname,
            });
          },
          fail: res => {
            this.setData({
              onname: '',
            });
          },
        });
      },
    });
  },

  recording({SSID: wifi_name = '', password: wifi_password =''}) {
    const { location = ''} = this.data;
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        wifi_name,
        wifi_password,
        op: 'addWifiRecord',
        location,
      },
      module: 'cm_wifi',
      success: res =>{
        console.log('====recording success',  res);
        }
    });
  },
});